import React, { useEffect, useMemo, useState } from 'react';
import { Card, Space, Button, Table, Modal, Form, Input, InputNumber, message, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

// 本地存储键名
const LS_KEY = 'authority-role-list';

// 生成一些初始树形角色数据
function genInitialRoles() {
  const now = new Date();
  const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  return [
    {
      id: 1,
      name: '系统管理员',
      sort: 1,
      createTime: fmt(now),
      children: [
        { id: 11, name: '用户管理员', sort: 1, createTime: fmt(now) },
        { id: 12, name: '证书管理员', sort: 2, createTime: fmt(now) },
      ],
    },
    {
      id: 2,
      name: '运营管理员',
      sort: 2,
      createTime: fmt(now),
      children: [
        { id: 21, name: '活动运营', sort: 1, createTime: fmt(now) },
        { id: 22, name: '内容运营', sort: 2, createTime: fmt(now) },
      ],
    },
    { id: 3, name: '访客', sort: 99, createTime: fmt(now) },
  ];
}

function loadFromLS() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return genInitialRoles();
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : genInitialRoles();
  } catch (e) {
    return genInitialRoles();
  }
}

function saveToLS(list) {
  localStorage.setItem(LS_KEY, JSON.stringify(list));
}

export default function Role() {
  const [loading, setLoading] = useState(false);
  const [roleList, setRoleList] = useState(() => loadFromLS());
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [dialogOpen, setDialogOpen] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [form] = Form.useForm();

  // 扁平化角色用于分页统计
  const flatList = useMemo(() => {
    const out = [];
    const walk = (arr, parentId = null) => {
      for (const item of arr) {
        out.push({ ...item, parentId });
        if (item.children && item.children.length) walk(item.children, item.id);
      }
    };
    walk(roleList);
    return out.sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0));
  }, [roleList]);

  useEffect(() => {
    setPagination((p) => ({ ...p, total: flatList.length }));
  }, [flatList]);

  const columns = [
    { title: '角色名称', dataIndex: 'name', key: 'name' },
    { title: '排序', dataIndex: 'sort', key: 'sort', width: 90 },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 200 },
    {
      title: '类型', key: 'type', width: 120,
      render: (_, record) => record.children && record.children.length ? <Tag color="blue">父级</Tag> : <Tag>叶子</Tag>
    },
    {
      title: '操作', key: 'actions', width: 180,
      render: (_, record) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => onEdit(record)}>编辑</Button>
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => onDelete(record)}>删除</Button>
          {!record.parentId && (
            <Button size="small" icon={<PlusOutlined />} onClick={() => onAddChild(record)}>加子级</Button>
          )}
        </Space>
      )
    }
  ];

  const onAddRoot = () => {
    setIsEdit(false);
    form.resetFields();
    setDialogOpen(true);
  };

  const onAddChild = (parent) => {
    setIsEdit(false);
    form.resetFields();
    form.setFieldsValue({ parentId: parent.id });
    setDialogOpen(true);
  };

  const onEdit = (record) => {
    setIsEdit(true);
    form.setFieldsValue({ id: record.id, name: record.name, sort: record.sort, parentId: record.parentId ?? null });
    setDialogOpen(true);
  };

  const onDelete = (record) => {
    Modal.confirm({
      title: '确认删除此角色？',
      content: `角色：${record.name}`,
      okText: '删除',
      okButtonProps: { danger: true },
      onOk: () => {
        const removeNode = (arr, id) => arr.filter((n) => {
          if (n.children) n.children = removeNode(n.children, id);
          return n.id !== id;
        });
        const newList = removeNode([...roleList], record.id);
        setRoleList(newList);
        saveToLS(newList);
        message.success('已删除');
      }
    });
  };

  const onModalOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const now = new Date();
      const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;

      let newList = [...roleList];
      if (isEdit && values.id) {
        const updateNode = (arr) => arr.map((n) => {
          if (n.id === values.id) {
            return { ...n, name: values.name, sort: values.sort ?? n.sort };
          }
          if (n.children) return { ...n, children: updateNode(n.children) };
          return n;
        });
        newList = updateNode(newList);
        message.success('已更新角色');
      } else {
        const newNode = {
          id: Date.now(),
          name: values.name,
          sort: values.sort ?? 99,
          createTime: fmt(now),
        };
        if (values.parentId) {
          const addChild = (arr) => arr.map((n) => {
            if (n.id === values.parentId) {
              const children = Array.isArray(n.children) ? [...n.children, newNode] : [newNode];
              return { ...n, children };
            }
            if (n.children) return { ...n, children: addChild(n.children) };
            return n;
          });
          newList = addChild(newList);
        } else {
          newList.push(newNode);
        }
        message.success('已新增角色');
      }
      setRoleList(newList);
      saveToLS(newList);
      setDialogOpen(false);
    } catch (e) {
      // 校验失败
    } finally {
      setLoading(false);
    }
  };

  const onModalCancel = () => setDialogOpen(false);

  const onTableChange = (paginationCfg) => {
    setPagination((p) => ({ ...p, current: paginationCfg.current, pageSize: paginationCfg.pageSize }));
  };

  return (
    <Card title="角色管理" extra={<Space><Button type="primary" icon={<PlusOutlined />} onClick={onAddRoot}>新增角色</Button></Space>}>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={roleList}
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          total: flatList.length,
          showTotal: (t) => `共 ${t} 条`,
        }}
        onChange={onTableChange}
        expandable={{ defaultExpandAllRows: true }}
      />

      <Modal
        title={isEdit ? '编辑角色' : '新增角色'}
        open={dialogOpen}
        onOk={onModalOk}
        onCancel={onModalCancel}
        okText={isEdit ? '保存' : '新增'}
        confirmLoading={loading}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="id" noStyle>
            <Input type="hidden" />
          </Form.Item>
          <Form.Item label="父级角色 ID" name="parentId">
            <InputNumber style={{ width: '100%' }} placeholder="留空表示新增为根角色" />
          </Form.Item>
          <Form.Item label="角色名称" name="name" rules={[{ required: true, message: '请输入角色名称' }]}>
            <Input placeholder="例如：系统管理员" />
          </Form.Item>
          <Form.Item label="排序" name="sort">
            <InputNumber min={0} style={{ width: '100%' }} placeholder="默认为 99" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}